package com.linghang.wusthelper.spider.jwc;

import com.linghang.wusthelper.entity.primary.CourseStage;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.ArrayList;
import java.util.List;

/**
 * @author origin
 * 选课阶段爬虫
 */
public class SelectCourseStageSpider implements PageProcessor {

    private List<CourseStage> courseStageList = new ArrayList<>();

    private Site site = Site.me()
            .setRetryTimes(3)
            .setTimeOut(3000)
            .addHeader("Connection", "keep-alive")
            .addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
            .addHeader("Accept-Encoding", "gzip,deflate,sdch")
            .addHeader("Accept-Language", "zh-CN,zh;q=0.8")
            .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36")
            .addHeader("Cache-Control","no-cache")
            .addHeader("Host","jwxt.wust.edu.cn")
            .setDomain("jwxt.wust.edu.cn");

    public SelectCourseStageSpider(String JSESSIOID,String SERVERID,List<CourseStage> courseStageList){
        site.addCookie("JSESSIONID",JSESSIOID);
        site.addCookie("SERVERID",SERVERID);
        this.courseStageList = courseStageList;
    }

    @Override
    public void process(Page page) {

        String path = "//*[@id=\"mxh\"]/tbody/tr[1]";
        int i = 1;
        while (page.getHtml().xpath(path).get() != null) {
            String str = "//*[@id=\"" + i + "\"]";
            String no = page.getHtml().xpath(str + "/td[1]/text()").get().replaceAll(" ","");
            String schoolTerm = page.getHtml().xpath(str + "/td[2]/text()").get();
            String category = page.getHtml().xpath(str + "/td[3]/text()").get();
            String stage = page.getHtml().xpath(str + "/td[4]/text()").get();
            String startTime = page.getHtml().xpath(str + "/td[5]/text()").get();
            String endTime = page.getHtml().xpath(str + "/td[6]/text()").get();
            String zzdxklbname = page.getHtml().xpath(str + "/td[7]/a/@onclick").regex("zzdxklbname=(.*?)&type").get();
            CourseStage courseStage = new CourseStage();
            courseStage.setNo(Integer.valueOf(no));
            courseStage.setSchoolTerm(schoolTerm);
            courseStage.setCategory(category);
            courseStage.setStage(stage);
            courseStage.setStartTime(startTime);
            courseStage.setEndTime(endTime);
            courseStage.setZzdxklbname(zzdxklbname);

            courseStageList.add(courseStage);
            i++;
            path = "/*[@id=\"mxh\"]/tbody/tr["+i+"]";
        }
    }

    @Override
    public Site getSite() {
        return site;
    }
}
